<?php

/**
 * Created by PhpStorm.
 * Script Name: Setting.php
 * Create: 2020/5/24 上午10:25
 * Description: 站点配置
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace app\admin\controller;
use app\common\model\Task as TaskM;
use app\constants\Common;
use app\constants\Media;
use app\constants\Task as TaskConst;

class Task extends Botbase
{
    /**
     * @var TaskM
     */
    protected $model;
    /**
     * @var array
     */
    private $tabList;

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new TaskM();
        $this->tabList = [
            'todo' => [
                'title' => '待发送',
                'href' => url('index', ['name' => 'todo'])
            ],
            'done' => [
                'title' => '已发送',
                'href' => url('index', ['name' => 'done'])
            ],
        ];
    }

    /**
     *
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @author: fudaoji<fdj@kuryun.cn>
     */
    public function index(){
        $name = input('name', 'todo');
        if (request()->isPost()) {
            $post_data = input('post.');
            $view_table = $this->model->field('id')
                ->where('admin_id', $this->adminInfo['id'])
                ->where('bot_id' , $this->bot['id']);
            !empty($post_data['search_key']) && $view_table = $view_table->where('title', 'like', '%' . $post_data['search_key'] . '%');
            if($name == 'todo'){
                $view_table = $view_table->where('(complete_time=0 and circle='.TaskConst::CIRCLE_SINGLE . ') or circle='.TaskConst::CIRCLE_DAILY);
                $order = ['t.plan_time' => 'asc'];
            }else{
                $view_table = $view_table->where('complete_time>0 and circle='.TaskConst::CIRCLE_SINGLE);
                $order = ['t.complete_time' => 'desc'];
            }
            $view_table = $view_table->buildSql();
            $params = [
                'alias' => 't',
                'join' => [
                    [$view_table . ' t1', 't1.id=t.id']
                ],
                'refresh' => true
            ];
            $total = $this->model->totalJoin($params);
            if ($total) {
                $list = $this->model->getListJoin(array_merge($params, [
                    'limit' => [$post_data['page'], $post_data['limit']],
                    'order' => $order,
                    'field' => 't.*'
                ]));
                foreach ($list as $k => $v){
                    if($v['wxids']){
                        $ids = explode(',', $v['wxids']);
                        if($member = model('admin/botMember')->getOneByMap([
                            'wxid' => $ids[0]
                        ])){
                            $v['wxids'] = $member['nickname'];
                            if(count($ids) > 1){
                                $v['wxids'] .= "等".count($ids)."个对象";
                            }
                        }else{
                            $v['wxids'] = "--";
                        }
                    }else{
                        $v['wxids'] = '用户分组：' . $v['member_tags'];
                    }


                    if($v['medias']){
                        $v['medias'] = json_decode($v['medias'], true);
                        $materials = [];
                        foreach ($v['medias'] as $item){
                            if($material = model('media_' . $item['type'])->getOneByMap([
                                'admin_id' => $v['admin_id'],
                                'id' => $item['id']
                            ], true, true)){
                                $materials[] = $item['type'] == 'text' ? $material['content'] : $material['title'];
                            }
                        }
                        $v['content'] = implode('、', $materials);
                    }else{
                        $v['content'] = '';
                    }
                    $list[$k] = $v;
                }
            }else{
                $list = [];
            }

            $this->success('success', '', ['total' => $total, 'list' => $list]);
        }

        $builder = new ListBuilder();
        $builder->setSearch([
            ['type' => 'text', 'name' => 'search_key', 'title' => '关键词', 'placeholder' => '内容']
        ])
            ->setTabNav($this->tabList, $name)
            ->setDataUrl(url('index', ['name' => $name]))
            ->addTopButton('addnew', ['title' => '新增群发'])
            ->addTableColumn(['title' => 'ID', 'field' => 'id', 'minWidth' => 60])
            ->addTableColumn(['title' => '任务名称', 'field' => 'title', 'minWidth' => 60])
            ->addTableColumn(['title' => '发送类型', 'field' => 'circle', 'minWidth' => 100, 'type' => 'enum', 'options' => TaskConst::circles()])
            ->addTableColumn(['title' => '回复内容', 'field' => 'content', 'minWidth' => 100])
            ->addTableColumn(['title' => '发送对象', 'field' => 'wxids', 'minWidth' => 100])
            ->addTableColumn(['title' => '计划发送时间', 'field' => 'plan_time', 'minWidth' => 180, 'type' => 'datetime']);
        if($name == 'done'){
            $builder->addTableColumn(['title' => '完成时间', 'field' => 'complete_time', 'minWidth' => 180, 'type' => 'datetime'])
                ->addTableColumn(['title' => '操作', 'minWidth' => 90, 'type' => 'toolbar'])
                ->addRightButton('self',['title' => '重发', 'href' => url('resetPost', ['id' => '__data_id__']), 'data-ajax' => 1, 'data-confirm' => 1]);
        }else{
            $builder->addTableColumn(['title' => '是否开启', 'field' => 'status', 'minWidth' => 70, 'type' => 'switch', 'options' => Common::status()])
                ->addTableColumn(['title' => '操作', 'minWidth' => 80, 'type' => 'toolbar'])
                ->addRightButton('edit');
        }

        return $builder->addRightButton('delete')->show();
    }

    public function resetPost()
    {
        $id = input('id', null);
        $data = $this->model->getOneByMap(['id' => $id, 'admin_id' => $this->adminInfo['id']], true, true);

        if (!$data) {
            $this->error('参数错误');
        }
        $this->model->updateOne([
            'id' => $id,
            'complete_time' => 0
        ]);
        $this->success('操作成功');
    }

    /**
     * 禁用/启用
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function forbidPost()
    {
        $id = input('id', null);
        $data = $this->model->getOneByMap(['id' => $id, 'admin_id' => $this->adminInfo['id']], true, true);

        if (!$data) {
            $this->error('参数错误');
        }
        $this->model->updateOne([
            'id' => $id,
            'status' => abs($data['status'] - 1)
        ]);
        $this->success('操作成功');
    }

    public function add()
    {
        $default = [
            'plan_time' => date('Y-m-d H:i:s'),
            'circle' => TaskConst::CIRCLE_SINGLE,
            'atall' => 0
        ];
        $material = [];
        $members = $this->getMembers();
        // 使用FormBuilder快速建立表单页面
        $builder = new FormBuilder();
        $builder->setMetaTitle('新增')
            ->setPostUrl(url('savePost'))
            ->addFormItem('title', 'text', '任务名称', '选填，不超过30字', [], 'maxlength=30')
            ->addFormItem('circle', 'radio', '发送类型', '发送类型', TaskConst::circles())
            ->addFormItem('plan_time', 'datetime', '发送时间', '不填则默认当前时间，发送类型选择“每天发送”时，会忽略日期而只取时间段', [], '')
            ->addFormItem('media', 'choose_media_multi', '选择素材', '选择素材', ['types' => Media::types()], 'required')
            ->addFormItem('atall', 'radio', '艾特全体', '针对群才有效', [0 => '否', 1 => '是'], 'required')
            ->addFormItem('zddx_legend', 'legend', '指定对象', '指定对象')
            ->addFormItem('member_tags', 'chosen_multi', '用户分组', '用户分组', model('memberTag')->getTitleToTitle($this->bot['id']))
            ->addFormItem('wxids', 'chosen_multi', '自由选择', '若填此项则用户分组的设置将失效', $members)
            ->setFormData($default);

        return $builder->show(['material' => $material]);
    }

    public function edit()
    {
        $id = input('id', null);
        $data = $this->model->getOneByMap(['id' => $id, 'admin_id' => $this->adminInfo['id']], true, true);

        if (!$data) {
            $this->error('参数错误');
        }
        $data['wxids'] = empty($data['wxids']) ? [] : explode(',', $data['wxids']);
        $data['member_tags'] = empty($data['member_tags']) ? [] : explode(',', $data['member_tags']);
        $materials = [];
        if($data['medias']){
            $data['medias'] = json_decode($data['medias'], true);
            foreach ($data['medias'] as $item){
                $m = model('media_' . $item['type'])->getOneByMap([
                    'admin_id' => $data['admin_id'],
                    'id' => $item['id']
                ], true, true);
                $m['type'] = $item['type'];
                $materials[] = $m;
            }
        }

        $members = $this->getMembers();
        // 使用FormBuilder快速建立表单页面
        $builder = new FormBuilder();
        $builder->setMetaTitle('编辑')
            ->setPostUrl(url('savePost'))
            ->addFormItem('id', 'hidden', 'ID', 'ID')
            ->addFormItem('title', 'text', '任务名称', '选填，不超过30字', [], 'maxlength=30')
            ->addFormItem('circle', 'radio', '发送类型', '发送类型', TaskConst::circles())
            ->addFormItem('plan_time', 'datetime', '发送时间', '不填则默认当前时间，发送类型选择“每天发送”时，会忽略日期而只取时间段', [], '')
            ->addFormItem('media', 'choose_media_multi', '选择素材', '可多选', ['types' => Media::types(), 'materials' => $materials], 'required')
            ->addFormItem('atall', 'radio', '艾特全体', '艾特全体', [0 => '否', 1 => '是'], 'required')
            ->addFormItem('status', 'radio', '状态', '状态', [1 => '启用', 0 => '禁用'])
            ->addFormItem('zddx_legend', 'legend', '指定对象', '指定对象')
            ->addFormItem('member_tags', 'chosen_multi', '用户分组', '用户分组', model('memberTag')->getTitleToTitle($this->bot['id']))
            ->addFormItem('wxids', 'chosen_multi', '自由选择', '若填此项则用户分组的设置将失效', $members)
            ->setFormData($data);

        return $builder->show();
    }

    public function savePost($jump_to = '/undefined', $data = [])
    {
        $post_data = input('post.');
        $post_data['admin_id'] = $this->adminInfo['id'];
        $post_data['bot_id'] = $this->bot['id'];
        if(empty($post_data['plan_time'])){
            $post_data['plan_time'] = time();
        }else{
            $post_data['plan_time'] = strtotime($post_data['plan_time']);
        }
        $post_data['plan_hour'] = date('H:i', $post_data['plan_time']);
        if(count($post_data['media_id_type']) > 0){
            $medias = [];
            foreach ($post_data['media_id_type'] as $id_type){
                list($id, $type) = explode('_', $id_type);
                $medias[] = ['id' => $id, 'type' => $type];
            }
            $post_data['medias'] = json_encode($medias, JSON_UNESCAPED_UNICODE);
            unset($post_data['media_id_type']);
        }else{
            $this->error('请选择素材');
        }
        if(empty($post_data[$this->pk])){
            $res = $this->model->addOne($post_data);
        }else {
            $res = $this->model->updateOne($post_data);
        }
        if($res){
            $this->success('数据保存成功', $jump_to);
        }else{
            $this->error('数据保存出错');
        }
    }
}